package com.evergrande.mybatis.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.evergrande.mybatis.service.UserInfoService;
import com.evergrande.mybatis.util.CookieUtils;

/**
 * Created by yyccbbz on 2016-8-11.
 */
@RequestMapping("rest/user")
@Controller
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    //定义cookieName
    public static final String USER_TICKET = "USER_TICKET";

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "login",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> login(@RequestParam("username") String username, @RequestParam("password") String password,
                                     HttpServletRequest request, HttpServletResponse response) {
        String ticket = this.userInfoService.login(username, password);
        Map<String, Object> result = new HashMap<String, Object>(1);
        if (null == ticket) {
            // 登录失败
            result.put("status", "500");
        } else {
            // 成功
            result.put("status", "200");
            // 将ticket写入到cookie中
            // cookie是会话级别
            CookieUtils.setCookie(request, response, USER_TICKET, ticket);
        }
        System.out.println("ticket:"+ticket);
        for (Object o : result.values()) {
            System.out.println("value= " + o);
        }
        return result;
    }

}
